package com.jse.oo.design.pattern.creational.singleton;

/**
 * 参考资料：
 * 双向检查优化：https://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
 * @author zenghua233
 *
 */
public class LazySingletion {

	private volatile LazySingletion singleton;
	
	/**
	 * 不在方法上面加synchronized，避免已经实例化了还要用synchronized，性能不好
	 * @return
	 */
	public LazySingletion getSingleton() {
		//
		if (singleton == null) {
			//这个空隙，singleton可能被其他线程实例化了，所以singleton要加volatile
			synchronized(this) {
				if (singleton == null) {
					singleton = new LazySingletion();
				}
			}
		}
		
		return singleton;
	}
	
}
